package com.lepu.datajackson.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.lepu.datajackson.annotation.SensitiveInfo;
import com.lepu.datajackson.config.SensitiveStrategy;

import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏序列化器
 */
public class SensitiveJsonSerializer  extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategy sensitiveStrategy;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(sensitiveStrategy.desensitizer().apply(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        SensitiveInfo annotation = beanProperty.getAnnotation(SensitiveInfo.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
            this.sensitiveStrategy = annotation.value();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}
